#!/usr/bin/env python3
"""
拉曼光谱数据预处理主程序

使用方法:
    python main.py <excel_file_path>

示例:
    python main.py 拉曼.xlsx
"""

import sys
import os
import argparse
from pathlib import Path

# 添加项目根目录到Python路径
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

from raman_preprocessing.exceptions import RamanPreprocessingError


def parse_arguments():
    """解析命令行参数"""
    parser = argparse.ArgumentParser(
        description='拉曼光谱数据预处理工具',
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
示例用法:
  python main.py 拉曼.xlsx                    # 处理拉曼.xlsx文件
  python main.py data/spectra.xlsx           # 处理指定路径的文件
        """
    )
    
    parser.add_argument(
        'input_file',
        type=str,
        help='输入的Excel文件路径'
    )
    
    parser.add_argument(
        '-o', '--output-dir',
        type=str,
        default='output',
        help='输出目录 (默认: output)'
    )
    
    parser.add_argument(
        '-v', '--verbose',
        action='store_true',
        help='显示详细处理信息'
    )
    
    return parser.parse_args()


def main():
    """主程序入口"""
    try:
        args = parse_arguments()
        
        # 验证输入文件存在
        input_path = Path(args.input_file)
        if not input_path.exists():
            print(f"错误: 输入文件 '{args.input_file}' 不存在")
            sys.exit(1)
        
        if not input_path.suffix.lower() in ['.xlsx', '.xls']:
            print(f"错误: 输入文件必须是Excel格式 (.xlsx 或 .xls)")
            sys.exit(1)
        
        # 创建输出目录
        output_dir = Path(args.output_dir)
        output_dir.mkdir(exist_ok=True)
        
        print(f"开始处理文件: {args.input_file}")
        print(f"输出目录: {args.output_dir}")
        
        # 导入预处理模块
        from raman_preprocessing import (
            DataReader, PreprocessingEngine, 
            CombinationGenerator, OutputManager
        )
        
        # 初始化组件
        data_reader = DataReader(args.input_file)
        preprocessing_engine = PreprocessingEngine()
        combination_generator = CombinationGenerator()
        output_manager = OutputManager(args.output_dir)
        
        # 读取数据
        print("正在读取Excel文件...")
        labels, spectra_data = data_reader.read_excel()
        print(f"成功读取 {len(labels)} 个样本，{spectra_data.shape[1]} 个波长点")
        
        # 生成所有预处理组合
        combinations = combination_generator.generate_combinations()
        print(f"将生成 {len(combinations)} 种预处理组合")
        
        # 处理每种组合
        successful_files = []
        failed_combinations = []
        
        for i, combination in enumerate(combinations, 1):
            try:
                if args.verbose:
                    print(f"[{i}/{len(combinations)}] 处理组合: {combination['name']}")
                else:
                    print(f"处理进度: {i}/{len(combinations)}", end='\r')
                
                # 应用预处理
                processed_data = preprocessing_engine.process_combination(spectra_data, combination)
                
                # 保存结果
                output_path = output_manager.save_processed_data(
                    labels, processed_data, combination, args.input_file
                )
                
                successful_files.append(output_path)
                
                if args.verbose:
                    print(f"    已保存: {Path(output_path).name}")
                    
            except Exception as e:
                failed_combinations.append((combination['name'], str(e)))
                if args.verbose:
                    print(f"    错误: {str(e)}")
        
        # 输出处理结果
        print(f"\n处理完成!")
        print(f"成功生成 {len(successful_files)} 个文件")
        
        if failed_combinations:
            print(f"失败的组合 ({len(failed_combinations)} 个):")
            for name, error in failed_combinations:
                print(f"  - {name}: {error}")
        
        if args.verbose and successful_files:
            print(f"\n生成的文件:")
            for file_path in successful_files:
                print(f"  - {Path(file_path).name}")
        
        print(f"\n所有文件已保存到: {args.output_dir}")
        
    except RamanPreprocessingError as e:
        print(f"预处理错误: {e}")
        sys.exit(1)
    except KeyboardInterrupt:
        print("\n用户中断处理")
        sys.exit(1)
    except Exception as e:
        print(f"未预期的错误: {e}")
        sys.exit(1)


if __name__ == "__main__":
    main()